//
//  CCKSZCViewController.m
//  cc
//
//  Created by ZLQ on 2016/10/25.
//  Copyright © 2016年 hbyj. All rights reserved.
//

#import "CCKSZCViewController.h"
#import "AFNetworking.h"
#import "SVProgressHUD.h"
@interface CCKSZCViewController ()
{
    UIView *bgView;
    UITextField *phone;
    UITextField *code;
    UINavigationBar *customNavigationBar;
    UIButton *yzButton;
}

@property(nonatomic, copy) NSString *oUserPhoneNum;
@property(assign, nonatomic) NSInteger timeCount;
//计时器
@property(strong, nonatomic) NSTimer *timer;
//验证码
@property(copy, nonatomic) NSString *smsId;

@end

@implementation CCKSZCViewController
/**
 *
 *  调出导航栏
 */
-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden=NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title=@"注册1/3";
    //设置导航栏颜色
    [[UINavigationBar appearance]setBarTintColor:RGBColor(240, 140, 50)];
    //设置背景颜色
    self.view.backgroundColor=[UIColor colorWithRed:240/255.0f green:240/255.0f blue:240/255.0f alpha:1];
    UIBarButtonItem *addBtn = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(clickaddBtn)];
    [addBtn setImage:[UIImage imageNamed:@"v2_goback"]];
    [addBtn setImageInsets:UIEdgeInsetsMake(0, -15, 0, 15)];
    addBtn.tintColor=[UIColor colorWithRed:248/255.0f green:144/255.0f blue:34/255.0f alpha:1];
    [self.navigationItem setLeftBarButtonItem:addBtn];
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 40, 50, 20)];
    [button setTitle:@"返回" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
    [button addTarget:self action:@selector(clickaddBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    [self createTextFields];
}

/**
 *  点击返回按钮，返回上一级菜单
 */
-(void)clickaddBtn
{
    //[self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)createTextFields
{
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(30, 75, self.view.frame.size.width-90, 30)];
    label.text=@"请输入您的手机号码";
    label.textColor=[UIColor grayColor];
    label.textAlignment=NSTextAlignmentLeft;
    label.font=[UIFont systemFontOfSize:13];
    
    [self.view addSubview:label];
    
    
    CGRect frame=[UIScreen mainScreen].bounds;
    bgView=[[UIView alloc]initWithFrame:CGRectMake(10, 110, frame.size.width-20, 100)];
    bgView.layer.cornerRadius=3.0;
    bgView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:bgView];
    
    phone=[self createTextFielfFrame:CGRectMake(100, 10, 200, 30) font:[UIFont systemFontOfSize:14] placeholder:@"11位手机号"];
    phone.clearButtonMode = UITextFieldViewModeWhileEditing;
    phone.keyboardType=UIKeyboardTypeNumberPad;
    
    //phone.text=@"15527002684";
    
    code=[self createTextFielfFrame:CGRectMake(100, 60, 90, 30) font:[UIFont systemFontOfSize:14]  placeholder:@"6位数字" ];
    code.clearButtonMode = UITextFieldViewModeWhileEditing;
    //code.text=@"mojun1992225";
    //密文样式
    code.secureTextEntry=YES;
    code.keyboardType=UIKeyboardTypeNumberPad;
    
    
    UILabel *phonelabel=[[UILabel alloc]initWithFrame:CGRectMake(20, 12, 50, 25)];
    phonelabel.text=@"手机号";
    phonelabel.textColor=[UIColor blackColor];
    phonelabel.textAlignment=NSTextAlignmentLeft;
    phonelabel.font=[UIFont systemFontOfSize:14];
    
    UILabel *codelabel=[[UILabel alloc]initWithFrame:CGRectMake(20, 62, 50, 25)];
    codelabel.text=@"验证码";
    codelabel.textColor=[UIColor blackColor];
    codelabel.textAlignment=NSTextAlignmentLeft;
    codelabel.font=[UIFont systemFontOfSize:14];
    
    
    yzButton=[[UIButton alloc]initWithFrame:CGRectMake(bgView.frame.size.width-100-20, 62, 100, 30)];
    //yzButton.layer.cornerRadius=3.0f;
    //yzButton.backgroundColor=[UIColor colorWithRed:240/255.0f green:240/255.0f blue:240/255.0f alpha:1];
    [yzButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [yzButton setTitleColor:[UIColor colorWithRed:248/255.0f green:144/255.0f blue:34/255.0f alpha:1] forState:UIControlStateNormal];
    yzButton.titleLabel.font=[UIFont systemFontOfSize:13];
    [yzButton addTarget:self action:@selector(getValidCode:) forControlEvents:UIControlEventTouchUpInside];
    
    [bgView addSubview:yzButton];
    
    UIImageView *line1=[self createImageViewFrame:CGRectMake(20,50,bgView.frame.size.width-120,1) imageName:nil color:[UIColor colorWithRed:180/255.0f green:180/255.0f blue:180/255.0f alpha:.3]];
    
    
    //‘下一步’ 按钮
    UIButton *landBtn=[self createButtonFrame:CGRectMake(10,bgView.frame.size.height+bgView.frame.origin.y+30,self.view.frame.size.width-20,37)backImageName:nil title:@"下一步" titleColor:[UIColor whiteColor] font:[UIFont systemFontOfSize:17] target:self action:@selector(next:)];
    landBtn.backgroundColor=[UIColor colorWithRed:248/255.0f green:144/255.0f blue:34/255.0f alpha:1];
    
    landBtn.layer.cornerRadius=5.0f;
    
    
    [bgView addSubview:phone];
    [bgView addSubview:code];
    
    [bgView addSubview:phonelabel];
    [bgView addSubview:codelabel];
    [bgView addSubview:line1];
    [self.view addSubview:landBtn];
}

-(UITextField *)createTextFielfFrame:(CGRect)frame font:(UIFont *)font placeholder:(NSString *)placeholder
{
    UITextField *textField=[[UITextField alloc]initWithFrame:frame];
    
    textField.font=font;
    
    textField.textColor=[UIColor grayColor];
    
    textField.borderStyle=UITextBorderStyleNone;
    
    textField.placeholder=placeholder;
    
    return textField;
}

-(UIImageView *)createImageViewFrame:(CGRect)frame imageName:(NSString *)imageName color:(UIColor *)color
{
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:frame];
    
    if (imageName)
        
    {
        imageView.image=[UIImage imageNamed:imageName];
    }
    if (color)
        
    {
        imageView.backgroundColor=color;
    }
    
    return imageView;
}

-(UIButton *)createButtonFrame:(CGRect)frame backImageName:(NSString *)imageName title:(NSString *)title titleColor:(UIColor *)color font:(UIFont *)font target:(id)target action:(SEL)action
{
    UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame=frame;
    if (imageName)
    {
        [btn setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    }
    
    if (font)
    {
        btn.titleLabel.font=font;
    }
    
    if (title)
    {
        [btn setTitle:title forState:UIControlStateNormal];
    }
    if (color)
    {
        [btn setTitleColor:color forState:UIControlStateNormal];
    }
    if (target&&action)
    {
        [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    }
    return btn;
}

/**
 点击获取验证码
 
 @param sender 参数
 */
- (void)getValidCode:(UIButton *)sender
{
    if ([phone.text isEqualToString:@""])
    {
        [SVProgressHUD showWithStatus:@"请输入手机号"];
        return;
    }
    else if (phone.text.length < 11)
    {
        [SVProgressHUD showWithStatus:@"请输入正确格式的手机号"];
        return;
    }
    _oUserPhoneNum =phone.text;
    
    //__weak MMZCHMViewController *weakSelf = self;
    
    
    /*************/
    /*
     [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:@"13313125432" zone:@"86" customIdentifier:nil result:^(NSError *error) {
     if (!error) {
     NSLog(@"获取验证码成功");
     yzButton.userInteractionEnabled = NO;
     } else {
     NSLog(@"错误信息：%@",error);
     }
     }];
     */
    /*************/
    
    NSDictionary *parmar = @{@"phone":phone.text};
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager POST:@"http://text.dawenkeji.com/Validate.asmx/SendYZM" parameters:parmar progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        sender.userInteractionEnabled = NO;
        self.timeCount = 60;
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(reduceTime:) userInfo:sender repeats:YES];
        
        NSLog(@"上传成功 %@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"上传失败 %@",error);
        
    }];
}

//计时器方法
- (void)reduceTime:(NSTimer *)codeTimer {
    self.timeCount--;
    if (self.timeCount == 0) {
        [yzButton setTitle:@"重新获取验证码" forState:UIControlStateNormal];
        [yzButton setTitleColor:[UIColor colorWithRed:
                                 248/255.0f green:144/255.0f blue:34/255.0f alpha:1] forState:UIControlStateNormal];
        UIButton *info = codeTimer.userInfo;
        info.enabled = YES;
        yzButton.userInteractionEnabled = YES;
        [self.timer invalidate];
    } else {
        NSString *str = [NSString stringWithFormat:@"%lu秒后重新获取", self.timeCount];
        [yzButton setTitle:str forState:UIControlStateNormal];
        yzButton.userInteractionEnabled = NO;
        
    }
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [phone resignFirstResponder];
    
}

/**
 点击下一步
 */
-(void)next:(UIButton *)sender
{
    
    //    if (code.text.length==0) {
    //        [SMSSDK commitVerificationCode:code.text phoneNumber:@"18635122339" zone:@"86" result:^(NSError *error) {
    //
    //            if (!error) {
    //                NSLog(@"验证成功");
    //            }
    //            else
    //            {
    //                NSLog(@"错误信息:%@",error);
    //            }
    //        }];
    //    }
    if ([phone.text isEqualToString:@""]) {
        [SVProgressHUD showInfoWithStatus:
         @"亲，请填写手机号码"];
        return;
    }else if
        (phone.text.length < 11){
            [SVProgressHUD showInfoWithStatus:@"手机号码不正确"];
            return;
        }else if
            ([code.text isEqualToString:@""]){
                [SVProgressHUD showInfoWithStatus:
                 @"验证码不能为空"];
                return;
            }else if (code.text.length != 6){
                [SVProgressHUD showInfoWithStatus:
                 @"验证码格式不正确"];
            }
    
    NSDictionary *parmar = @{@"phone":phone.text,@"yzm":code.text};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:@"http://text.dawenkeji.com/Validate.asmx/register" parameters:parmar progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"上传成功 %@",responseObject);
        if (responseObject[@"phone"]==phone.text && responseObject[@"yzm"]==code.text) {
            
            //SettingPassWordController *setting = [[SettingPassWordController alloc] init];
            
            //setting.phone = phone;
            
            //[self.navigationController pushViewController:setting animated:YES];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"上传失败 %@",error);
        
        
    }];
    
}

@end
